<template>
  <div class="page-container relative">
    <BaseCollapse title="基础信息">
      <DynamicForm :config="basicConfig" :questions="basicQuestions" ref="base" />
    </BaseCollapse>

    <BaseCollapse title="归还档案列表">
      <DynamicForm :config="returnListConfig" :questions="returnListQuestions" ref="returnList" v-if="['ADD', 'UPDATE'].includes(state.showType)" />

      <DynamicTable :config="returnListTableConfig" :tables="returnListViewTable" v-if="['VIEW'].includes(state.showType)"></DynamicTable>

      <!-- <div style="display: flex; align-items: center; margin-bottom: 20px" v-if="['CONFIRM'].includes(state.showType)">
        扫描档案编码进行归还确认: <a-input placeholder="请扫描或输入" style="width: 350px; margin-left: 20px" @change.native="confirmChange"></a-input>
      </div> -->
      <DynamicTable :config="returnListConfirmTableConfig" :tables="returnListConfirmTable" ref="returnList" v-if="['CONFIRM'].includes(state.showType)">
        <template #isReturnTitle>
          <span><i style="color: #f00">* </i>是否归还</span>
        </template>

        <template #isReturn="{ column, text, record }">
          <a-select v-model:value="record.isReturn" style="width: 100%">
            <a-select-option value="0">否</a-select-option>
            <a-select-option value="1">是</a-select-option>
          </a-select>
        </template>
      </DynamicTable>
    </BaseCollapse>

    <!-- <BaseCollapse v-if="['CONFIRM'].includes(state.showType)" title="审批意见">
      <DynamicForm :config="dyCommentConfig" :questions="dyCommentQuestions" ref="commentRef" />
    </BaseCollapse>

    <AuditRecord v-if="['VIEW'].includes(state.showType)" /> -->

    <ApprovalDetail v-if="['VIEW', 'CONFIRM'].includes(state.showType) && query.processInstanceId" :config="approvalConfig" @back="approvalGoBack"></ApprovalDetail>

    <div class="space-x-2 w-full text-center my-4">
      <a-button v-if="['VIEW', 'UPDATE'].includes(state.showType)" @click="goBack">返回</a-button>
      <a-button v-if="['ADD', 'UPDATE'].includes(state.showType)" @click="archivesReturnInfoSaveOpt(0)">暂存</a-button>
      <a-button v-if="['ADD', 'UPDATE'].includes(state.showType)" type="primary" @click="archivesReturnInfoSaveOpt(1)">提交</a-button>
      <!-- <a-button v-if="['CONFIRM'].includes(state.showType)" type="primary" @click="returnFilesConfirmOpt">提交</a-button> -->
      <a-button v-if="['VIEW'].includes(state.showType) && [1, 2].includes(state.status)" type="primary" @click="toUpdate">编辑</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import ApprovalDetail from '@/components/approval-details/index.vue';
import AuditRecord from '@/components/common/AuditRecord/index.vue';
import BaseCollapse from '@/components/common/BaseCollapse/index.vue';
import { DynamicForm, DynamicTable } from '@/components/public-template';
import { archivesBorrowFindFileListByBorrowInfoIds, archivesBorrowFindBorrowFileByFileName } from '@/config/api/archivesRenew';
import { Api, archivesReturnInfoSave, archivesReturnInfoReturnFilesConfirm, archivesReturnInfoReturnFilesPage } from '@/config/api/archivesToReturn';
import { Modal, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { filter } from 'rxjs/operators';
import { getCurrentInstance, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import indexService from './index.service';
import { Api as archivesBorrowApi } from '@/config/api/archivesBorrow';

const router = useRouter();
const { query } = useRoute();
const { proxy }: any = getCurrentInstance();

const state = reactive({
  showType: 'ADD', // enum 'ADD' 'VIEW' 'UPDATE' 'CONFIRM'
  status: null
});
state.showType = query.showType as string;

// 基础信息
const basicQuestions = reactive(indexService.getQuestions());
const basicConfig: any = {
  queryUrl: ['ADD'].includes(state.showType) ? Api.archivesReturnInfoAutoProductFormInfo : archivesBorrowApi.archivesBorrowGet,
  protType: ['ADD'].includes(state.showType) ? 'post' : 'get',
  urlName: ['ADD'].includes(state.showType) ? '' : query.id,
  noGetDataParams: true,
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true,
  beforeWithMethod: (data) => {
    state.status = data.status;
    return data;
  }
};

const approvalConfig: any = ref({
  title: '审批流程',
  showBackBtn: true, //显示返回按钮
  showAgreeBtn: true, //显示同意按钮
  showGoBackBtn: true, // 显示退回按钮
  showRejectBtn: true // 显示拒绝按钮
});

// 档案归还列表
// 申请
const returnListQuestions = reactive(indexService.getReturnListAddQuestions({ showType: query.showType }));
const returnListConfig: any = {
  labelCol: 8,
  wrapperCol: 16,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};
// 详情
const returnListViewTable = reactive(indexService.getReturnListViewQuestions());
const returnListTableConfig: any = {
  queryUrl: Api.archivesReturnInfoReturnFilesPage,
  protType: 'post',
  params: { id: query.id },
  scroll: {
    x: '2500px'
  }
};
// 归还确认
const returnListConfirmTable = reactive(indexService.getReturnListConfirmQuestions());
const returnListConfirmTableConfig: any = {
  scroll: {
    x: '2500px'
  },
  data: []
};

const dyCommentQuestions = reactive(indexService.getCommentQuestions());
const dyCommentConfig: any = {
  labelCol: 8,
  wrapperCol: 22,
  grid: 6,
  layout: 'vertical',
  cancelSave: true
};

const approvalGoBack = (cb: any) => {
  cb?.();
};

const returnListAllData = ref<Array<any>>([]);

const subscribeSub = proxy.$NotificationFormSub
  .getParams()
  .pipe(filter((res) => res !== 0))
  .subscribe((item) => {
    if (item.key === 'CUSTOMSELECTSERVE') {
      for (let i of returnListAllData.value) {
        if (item.value.data.key === i.borrowInfoId) {
          for (let j in i) {
            for (let k in returnListQuestions[0].value[item.value.index]) {
              if (k === j) {
                returnListQuestions[0].value[item.value.index][k] = i[j];
                returnListQuestions[0].value[item.value.index].borrowInfoId = i.borrowInfoId;

                // 计划时间显示格式调整
                if (k === 'planReturnTime') {
                  returnListQuestions[0].value[item.value.index]['planReturnTime'] = dayjs(i[j]).format('YYYY.MM.DD HH:mm:ss');
                }

                // 实际时间显示格式调整
                returnListQuestions[0].value[item.value.index]['actualReturnTime'] = dayjs().format('YYYY.MM.DD HH:mm:ss');
              }
            }
          }
        }
      }
    }
  });

onMounted(() => {
  if (['ADD', 'UPDATE'].includes(state.showType)) {
    getFindBorrowFileByFileName();
  }

  if (['ADD'].includes(state.showType)) {
    getFileList();
  }

  if (['UPDATE', 'CONFIRM'].includes(state.showType)) {
    returnFilesPageOpt();
  }
  if (['VIEW'].includes(state.showType)) {
    approvalConfig.value.showBackBtn = false;
    approvalConfig.value.showAgreeBtn = false;
    approvalConfig.value.showGoBackBtn = false;
    approvalConfig.value.showRejectBtn = false;
  }
});

onBeforeUnmount(() => {
  subscribeSub && subscribeSub.unsubscribe();
  proxy.$NotificationFormSub.clearParams();
});

// 获取归还档案列表
const getFileList = () => {
  archivesBorrowFindFileListByBorrowInfoIds({ borrowInfoIds: JSON.parse(window.sessionStorage.getItem('ids')) }).then((res) => {
    if (res && res.success) {
      for (let i of res.data) {
        i.planReturnTime = i.planReturnTime && dayjs(i.planReturnTime).format('YYYY.MM.DD HH:mm:ss'); // 计划时间显示格式调整
        i.actualReturnTime = i.actualReturnTime && dayjs().format('YYYY.MM.DD HH:mm:ss'); // 实际时间显示格式调整
      }
      returnListQuestions[0].value = [...res.data];
    }
  });
};

// 归还档案列表获取文件名称
const getFindBorrowFileByFileName = () => {
  archivesBorrowFindBorrowFileByFileName({ keyWord: '', isRenew: false }).then((res) => {
    if (res && res.success) {
      let arr = [];
      for (let i of res.data) {
        arr.push({ label: i.filename, value: i.borrowInfoId, key: i.borrowInfoId });
      }

      // 归还档案列表（申请）
      if (['ADD', 'UPDATE'].includes(state.showType)) {
        for (let i = 0; i < returnListQuestions[0].state.columns.length; i++) {
          const item = returnListQuestions[0].state.columns[i];
          if (item.key == 'filename') {
            item.options = [...arr];
            break;
          }
        }
      }

      returnListAllData.value = [...res.data];
    }
  });
};

const returnFilesObj = reactive<{ allDataArr: Array<any>; displayArr: Array<any> }>({
  allDataArr: [], // 所有返回数据
  displayArr: [] // 当前显示数据
});

// 归还档案详情分页列表
const returnFilesPageOpt = () => {
  archivesReturnInfoReturnFilesPage({ id: query.id }).then((res) => {
    if (res && res.data) {
      let arr = [];
      for (let i of res.data) {
        let obj = { ...i };
        delete obj['fileListList'];
        i.fileListList.filename = i.fileListList.name; // 文件名称处理
        obj = Object.assign(obj, i.fileListList, { remark: obj.remark });
        arr.push(obj);
      }
      returnListQuestions[0].value = [...arr];

      if (['CONFIRM'].includes(state.showType)) {
        returnListConfirmTableConfig.data = [...res.data]; // 初始化赋值
        returnList.value.getData();
        returnFilesObj.allDataArr = [...res.data];
      }
    }
  });
};

// 归还确认，输入框输入值改变事件
const confirmChange = (e) => {
  returnFilesObj.displayArr.length = 0;

  for (let i of returnFilesObj.allDataArr) {
    if (e.target.value === i.fileListList.filesBoxCode) {
      i.isReturn = '1';
      returnFilesObj.displayArr.push(i);
    }
  }

  if (e.target.value === '') {
    returnListConfirmTableConfig.data = [...returnFilesObj.allDataArr];
  } else {
    returnListConfirmTableConfig.data = [...returnFilesObj.displayArr];
  }

  returnList.value.getData();
};

const base = ref(null); // 基础信息
const returnList = ref(null); // 归还档案列表

// 保存
const archivesReturnInfoSaveOpt = (op) => {
  Modal.confirm({
    title: `是否确定${op === 0 ? '暂存' : '提交'}`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      let beforeSaveData = {
        baseData: {},
        returnListData: []
      };

      base.value.onFinish(({ billCode, creator, creatorName, department, departmentName, expirationReminder, createdTime }) => {
        beforeSaveData.baseData = Object.assign({}, { billCode, creator, creatorName, department, departmentName, expirationReminder, createdTime });
      });
      returnList.value.onFinish((data) => {
        for (let {
          filename,
          code,
          fileCode,
          filesBoxCode,
          borrowType,
          filesType,
          secretLevel,
          borrowCode,
          billCode,
          planReturnTime,
          actualReturnTime,
          returnType,
          overdueReason,
          remark,
          id,
          billId,
          borrowInfoId
        } of data.customTable) {
          let fileList = {};
          fileList['fileListList'] = { name: filename, code, fileCode, filesBoxCode, borrowType, filesType, secretLevel, billCode };
          planReturnTime = planReturnTime && planReturnTime.replace(new RegExp(/\./gm), '/'); // 火狐浏览器时间格式问题
          planReturnTime = planReturnTime && dayjs(planReturnTime).format('YYYY-MM-DD HH:mm:ss'); // 计划时间显示格式调整
          actualReturnTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 实际时间显示格式调整

          fileList = Object.assign(fileList, { borrowCode, borrowType, returnType, overdueReason, planReturnTime, actualReturnTime, remark });

          // 从待归还列表进入
          if (query.location === 'toReturned') {
            fileList['fileListList'].id = billId;
          } else {
            fileList['fileListList'].id = id;
          }

          if (typeof borrowInfoId !== 'undefined') {
            fileList['borrowInfoId'] = borrowInfoId;
          } else {
            fileList['borrowInfoId'] = id;
          }

          beforeSaveData.returnListData.push(fileList);
        }
      }, op == 0);

      const time = setTimeout(() => {
        if (op == 0 || (Object.keys(beforeSaveData.baseData).length > 0 && beforeSaveData.returnListData.length)) {
          let finalSaveData = { ...beforeSaveData.baseData, fileList: [...beforeSaveData.returnListData] };

          archivesReturnInfoSave({ ...finalSaveData, op, id: ['UPDATE'].includes(state.showType) ? query.id : '' }).then((res) => {
            if (res && res.success) {
              message.success(res.message);
              router.go(-1);
            }
          });
        }
        clearTimeout(time);
      }, 1000);
    }
  });
};

const goBack = () => {
  router.go(-1);
};

// 跳转编辑
const toUpdate = () => {
  router
    .replace({
      name: 'ArchivesManageAddReturn',
      query: {
        id: query.id,
        showType: 'UPDATE'
      }
    })
    .then(() => {
      router.go(0);
    });
};

const commentRef = ref(null);

// 归还档案确认
const returnFilesConfirmOpt = () => {
  Modal.confirm({
    title: '是否确定提交',
    okText: '确认',
    cancelText: '取消',
    onOk() {
      let infoVoList = [];

      for (let i of returnList.value?.dataList.value) {
        if (i.isReturn === null) {
          i.isReturn = '0';
        }
        infoVoList.push(i);
      }

      commentRef.value.onFinish((data) => {
        let { applyResult, remark } = data;

        archivesReturnInfoReturnFilesConfirm({ billId: query.id, applyResult, remark, infoVoList }).then((res) => {
          if (res && res.success) {
            message.success(res.message);
            goBack();
          }
        });
      });
    }
  });
};
</script>
